from app.utils.mysql_util import get_connection

def insert_refund(refund_data):
    conn = get_connection()
    cursor = conn.cursor()
    try:
        sql = """INSERT INTO refund (
            refund_id, refund_no, src_no, type, process_status,
            swap_trade_id, status, pay_account, pay_no, goods_amont,
            refund_amount, guarantee_mode, cs_status, sales_tid
        ) VALUES (
            %(refund_id)s, %(refund_no)s, %(src_no)s, %(type)s, %(process_status)s,
            %(swap_trade_id)s, %(status)s, %(pay_account)s, %(pay_no)s, %(goods_amont)s,
            %(refund_amount)s, %(guarantee_mode)s, %(cs_status)s, %(sales_tid)s
        ) ON DUPLICATE KEY UPDATE
            status = VALUES(status),
            process_status = VALUES(process_status),
            refund_amount = VALUES(refund_amount)
        """
        cursor.execute(sql, refund_data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()

def insert_refund_order(order_data):
    conn = get_connection()
    cursor = conn.cursor()
    try:
        sql = """INSERT INTO refund_order (
            order_id, redund_id, oid, tid, process_status,
            order_num, price, refund_num, total_amount
        ) VALUES (
            %(order_id)s, %(redund_id)s, %(oid)s, %(tid)s, %(process_status)s,
            %(order_num)s, %(price)s, %(refund_num)s, %(total_amount)s
        ) ON DUPLICATE KEY UPDATE
            process_status = VALUES(process_status),
            refund_num = VALUES(refund_num),
            total_amount = VALUES(total_amount)
        """
        cursor.execute(sql, order_data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close()

def insert_refund_logistics(logistics_data):
    conn = get_connection()
    cursor = conn.cursor()
    try:
        sql = """INSERT INTO refund_logistics (
            refund_id, refund_no, logistics_no, logistics_name,
            logistics_code, logistics_company, return_address,
            return_name, return_mobile, return_telno,
            receive_time, created, modified
        ) VALUES (
            %(refund_id)s, %(refund_no)s, %(logistics_no)s, %(logistics_name)s,
            %(logistics_code)s, %(logistics_company)s, %(return_address)s,
            %(return_name)s, %(return_mobile)s, %(return_telno)s,
            %(receive_time)s, %(created)s, %(modified)s
        ) ON DUPLICATE KEY UPDATE
            logistics_no = VALUES(logistics_no),
            logistics_name = VALUES(logistics_name),
            receive_time = VALUES(receive_time),
            modified = VALUES(modified)
        """
        cursor.execute(sql, logistics_data)
        conn.commit()
    except Exception as e:
        conn.rollback()
        raise e
    finally:
        cursor.close()
        conn.close() 